<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/news' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="header-btn">
      <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
    </div>
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%;"
    >
      <el-table-column sortable prop="swiperId" label="轮播图编号" width="300"></el-table-column>
      <el-table-column align="center" prop="swiperurl" label="轮播图" width="300">
        <template slot-scope="scope">
          <img :src="scope.row.swiperurl" width="100" height="100" />
        </template>
      </el-table-column>
      <el-table-column sortable prop="swiperIndex" label="排序编号" width="300"></el-table-column>
      <el-table-column prop="swipertime" label="修改时间" width="300">
        <template slot-scope="scope">
          <div>{{scope.row.swipertime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="swiperDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      @click="closeDialog('edit')"
    >
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="轮播图图片" prop="swiperurl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            action="/apis/admin/swiperuploadImg"
          >
            <img
              v-if="editForm.swiperurl"
              :src="editForm.swiperurl"
              class="avatar"
              width="80"
              height="80"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片顺序" prop="swiperIndex">
          <el-input
            size="small"
            type="number"
            v-model="editForm.swiperIndex"
            auto-complete="off"
            placeholder="数字越大,优先级越高"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../Comm/Pagination";
import {
  swiperList,
  swiperSave,
  swiperUpdate,
  swiperDelete
} from "../../ajax/index";
export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: "添加",
      editForm: {
        swiperId: "",
        swiperurl: "",
        swiperIndex: ""
      },
      // rules 表单验证
      rules: {
        swiperIndex: [
          { required: true, message: "请输入排序编号", trigger: "blur" }
        ],
        swiperurl: [{ required: true, message: "请选择图片", trigger: "blur" }]
      },
      formInline: {
        page: 1,
        limit: 10
      },
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    };
  },
  // 注册组件
  components: {
    Pagination
  },
  created() {
    this.getdata(this.formInline);
  },

  /**
   * 里面的方法只有被调用才会执行
   */

  methods: {
    // 获取角色列表
    getdata(parameter) {
      this.loading = true;
      swiperList(parameter)
        .then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$message({
              type: "info",
              message: res.msg
            });
          } else {
            this.listData = res.data;
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page;
            this.pageparm.pageSize = this.formInline.limit;
            this.pageparm.total = res.count;
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error("获取角色列表失败，请稍后再试！");
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getdata(this.formInline);
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改";
        this.editForm.swiperId = row.swiperId;
        this.editForm.swiperurl = row.swiperurl;
        this.editForm.swiperIndex = row.swiperIndex;
      } else {
        this.title = "添加";
        this.editForm.swiperId = "";
        this.editForm.swiperurl = "";
        this.editForm.swiperIndex = "";
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          [swiperSave, swiperUpdate]
            [this.editForm.swiperId ? 1 : 0](this.editForm)
            .then(res => {
              this.editFormVisible = false;
              this.loading = false;
              if (res.code) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "轮播图保存成功！"
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("轮播图保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },
    // 删除角色
    swiperDelete(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          swiperDelete({
            swiperId: row.swiperId
          })
            .then(res => {
              if (res.code) {
                this.$message({
                  type: "success",
                  message: "轮播图已删除！"
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.loading = false;
              this.$message.error("轮播图删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
      }
    },
    handleAvatarSuccess(res, file) {
      // this.editForm.swiperurl = URL.createObjectURL(file.raw);
      this.editForm.swiperurl = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.header-btn {
  margin: 20px 0px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  border: 1px dashed #d9d9d9;
}
</style>

 